package com.ruoyi.web.controller.system;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.system.domain.AntiDumping;
import com.ruoyi.system.service.IAntiDumpingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

/**
 * 反倾销海关编码Controller
 * 
 * @author ruoyi
 * @date 2025-02-07
 */
@RestController
@RequestMapping("/system/dumping")
public class AntiDumpingController extends BaseController
{
    @Autowired
    private IAntiDumpingService antiDumpingService;

    // 配置文件中存储文件路径
    @Value("${kuaiqiao.profile}")
    private String uploadDir;
    /**
     * 下载服务器上的文件
     *
     * @param fileName 要下载的文件名
     * @return 下载的文件
     */
    @PostMapping("/downloadFile")
    public ResponseEntity<InputStreamResource> downloadFile() throws IOException {
//        @RequestParam String fileName
        String fileName = "fanqingxiao.xlsx";
        // 构建文件路径
        String filePath = uploadDir + "/" + fileName;

        // 读取文件
        InputStream inputStream = new FileInputStream(filePath);

        // 获取文件的 MIME 类型（这里假设文件是 XLSX 格式）
        String mimeType = Files.probeContentType(Paths.get(filePath));
        if (mimeType == null) {
            mimeType = "application/octet-stream";  // 默认二进制流类型
        }

        // 创建输入流资源
        InputStreamResource resource = new InputStreamResource(inputStream);

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
        headers.add(HttpHeaders.CONTENT_TYPE, mimeType);
        headers.add(HttpHeaders.CONTENT_LENGTH, String.valueOf(Files.size(Paths.get(filePath))));

        // 返回文件流响应
        return ResponseEntity.ok()
                .headers(headers)
                .body(resource);
    }


    /**
     * 查询反倾销海关编码列表
     */
    @PreAuthorize("@ss.hasPermi('system:dumping:list')")
    @GetMapping("/list")
    public TableDataInfo list(AntiDumping antiDumping)
    {
        startPage();
        List<AntiDumping> list = antiDumpingService.selectAntiDumpingList(antiDumping);
        return getDataTable(list);
    }

    /**
     * 导出反倾销海关编码列表
     */
    @PreAuthorize("@ss.hasPermi('system:dumping:export')")
    @Log(title = "反倾销海关编码", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, AntiDumping antiDumping)
    {
        List<AntiDumping> list = antiDumpingService.selectAntiDumpingList(antiDumping);
        ExcelUtil<AntiDumping> util = new ExcelUtil<AntiDumping>(AntiDumping.class);
        util.exportExcel(response, list, "反倾销海关编码数据");
    }

    /**
     * 获取反倾销海关编码详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:dumping:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(antiDumpingService.selectAntiDumpingById(id));
    }

    /**
     * 新增反倾销海关编码
     */
    @PreAuthorize("@ss.hasPermi('system:dumping:add')")
    @Log(title = "反倾销海关编码", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AntiDumping antiDumping)
    {
        return toAjax(antiDumpingService.insertAntiDumping(antiDumping));
    }

    /**
     * 修改反倾销海关编码
     */
    @PreAuthorize("@ss.hasPermi('system:dumping:edit')")
    @Log(title = "反倾销海关编码", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AntiDumping antiDumping)
    {
        return toAjax(antiDumpingService.updateAntiDumping(antiDumping));
    }

    /**
     * 删除反倾销海关编码
     */
    @PreAuthorize("@ss.hasPermi('system:dumping:remove')")
    @Log(title = "反倾销海关编码", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(antiDumpingService.deleteAntiDumpingByIds(ids));
    }

    /**
     * 新增数据匹配
     */
    @PreAuthorize("@ss.hasPermi('system:matching:add')")
    @Log(title = "数据匹配", businessType = BusinessType.INSERT)
    @PostMapping("/upload")
    public JSONObject uploadFile(@RequestParam("file") MultipartFile file) {
        JSONObject res = new JSONObject();
        if (file.isEmpty()) {
            res.put("error", "文件不能为空");
            return res;
        }
        try {
            InputStream inputStream = file.getInputStream();
            AsyncManager.me().execute(AsyncFactory.importExcelDataFqx(inputStream));
            res.put("success","数据持续导入中，请稍后刷新查看～");
            res.put("code","200");
            antiDumpingService.importExcelData(inputStream);
            return res;
        } catch (Exception e) {
            res.put("error", e.getMessage());
            return res;
        }
    }
}
